<?php
/**
 * @copyright        2016 opencart.cn - All Rights Reserved
 * @link             http://www.guangdawangluo.com
 * @author           TL <mengwb@opencart.cn>
 * @created          2016-12-12 16:04:00
 * @modified         2016-12-12 16:39:36
 */

class ControllerExtensionPaymentQrcodeweipay extends Controller
{
    public function index()
    {
		$data['button_confirm'] = $this->language->get('button_confirm');

		$data['redirect'] = $this->url->link('extension/payment/qrcodeweipay/qrcode');

		return $this->load->view('extension/payment/qrcodeweipay', $data);
    }

	public function qrcode() {
		$this->load->language('extension/payment/qrcodeweipay');

		$this->document->setTitle($this->language->get('heading_title'));
		$this->document->addScript('catalog/view/javascript/qrcode.js');

		$data['heading_title'] = $this->language->get('heading_title');

		$data['breadcrumbs'] = array();

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/home')
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_checkout'),
			'href' => $this->url->link('checkout/checkout', '', true)
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_qrcode'),
			'href' => $this->url->link('extension/payment/qrcodeweipay/qrcode')
		);

        $data['text_qrcode_description'] = $this->language->get('text_qrcode_description');

		$this->load->model('checkout/order');

		$order_info = $this->model_checkout_order->getOrder($this->session->data['order_id']);

		$order_id = trim($order_info['order_id']);
		$data['order_id'] = $order_id;
		$subject = trim($this->config->get('config_name'));
		$currency = $this->config->get('qrcodeweipay_currency');
		$total_amount = trim($this->currency->format($order_info['total'], $currency, '', false));
        if (is_file(getcwd().'/callbacks/payment_qrcodeweipay.php')) {
            $notify_url = HTTP_SERVER . 'callbacks/payment_qrcodeweipay.php';//通知地址
        } else {
            //通知地址, 该方式需要配置伪静态规则，且要把文件callback/qrcodeweipay_callback.php删除
			$notify_url = HTTPS_SERVER . "payment_callback/qrcodeweipay"; //$this->url->link('qrcodeweipay/callback');
        }

		$options = array(
			'appid'			 =>  $this->config->get('qrcodeweipay_appid'),
			'appsecret'		 =>  $this->config->get('qrcodeweipay_appsecret'),
			'mch_id'			=>  $this->config->get('qrcodeweipay_mchid'),
			'partnerkey'		=>  $this->config->get('qrcodeweipay_key'),
			'cachepath'         =>  DIR_CACHE . 'wechat/'
		);

		\Wechat\Loader::config($options);
		$pay = new \Wechat\WechatPay();

		$result = $pay->getPrepayId(NULL, $subject, $order_id . '-' . time(), $total_amount * 100, $notify_url, $trade_type = "NATIVE", NULL, $currency);

		$data['error'] = '';
		$data['code_url'] = '';
		if($result === FALSE){
			$data['error_warning'] = $pay->errMsg;
		} else {
			$data['code_url'] = $result;
		}

		$data['action_success'] = $this->url->link('checkout/success');

		$data['column_left'] = $this->load->controller('common/column_left');
		$data['column_right'] = $this->load->controller('common/column_right');
		$data['content_top'] = $this->load->controller('common/content_top');
		$data['content_bottom'] = $this->load->controller('common/content_bottom');
		$data['footer'] = $this->load->controller('common/footer');
		$data['header'] = $this->load->controller('common/header');

		$this->response->setOutput($this->load->view('extension/payment/qrcodeweipay_qrcode', $data));
	}

	public function isOrderPaid() {
		$json = array();

		$json['result'] = false;

		if (isset($this->request->get['order_id'])) {
			$order_id = $this->request->get['order_id'];

			$this->load->model('checkout/order');
			$order_info = $this->model_checkout_order->getOrder($order_id);

			if ($order_info['order_status_id'] == $this->config->get('qrcodeweipay_order_status_id')) {
				$json['result'] = true;
			}
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function notifycallback() {
		$options = array(
			'appid'			 =>  $this->config->get('qrcodeweipay_appid'),
			'appsecret'		 =>  $this->config->get('qrcodeweipay_appsecret'),
			'mch_id'			=>  $this->config->get('qrcodeweipay_mchid'),
			'partnerkey'		=>  $this->config->get('qrcodeweipay_key'),
			'cachepath'         =>  DIR_CACHE . 'wechat/'
		);

		\Wechat\Loader::config($options);
		$pay = new \Wechat\WechatPay();
		$notifyInfo = $pay->getNotify();

		if ($notifyInfo === FALSE) {
			$this->log->write('Wechat Pay Error: ' . $pay->errMsg);
		} else {
			$this->log->write('Wechat Pay Verify Success! notifyInfo='.var_export($notifyInfo, true));
			if ($notifyInfo['result_code'] == 'SUCCESS' && $notifyInfo['return_code'] == 'SUCCESS') {
				$order_id = (int)$notifyInfo['out_trade_no'];
				$this->load->model('checkout/order');
				$order_info = $this->model_checkout_order->getOrder($order_id);
				if ($order_info) {
					$order_status_id = $order_info["order_status_id"];
					$this->log->write('order_status_id='.$order_status_id);
					$this->log->write('gdconfig_unpaid_status='.$this->config->get('gdconfig_unpaid_status'));
					if (!$order_status_id || $order_status_id == $this->config->get('gdconfig_unpaid_status')) {
						$this->log->write('Wechat Pay Addorderhistory');
						$this->model_checkout_order->addOrderHistory($order_id, $this->config->get('qrcodeweipay_order_status_id'));
					}
				}
				echo \Wechat\Lib\Tools::arr2xml(['return_code' => 'SUCCESS', 'return_msg' => 'DEAL WITH SUCCESS']);
			}
		}
	}
}
